<template>
  <div class="view-fill">
    <div class="app-container-flex">
      <FullScreen
        v-model="showDialog"
        :title="title"
        @returnBack="$emit('returnModify')"
      >
        <template v-slot:full-button>
          <el-button @click="save()">保存</el-button>
        </template>
        <div class="model-panel">
          <div class="model-panel-title">
            <p>品种信息</p>
          </div>
          <div class="model-panel-body">
            <!-- form -->
            <PageForm
              class="paddingBox order-model-formBox flex_wrap_start_start"
              v-model:ref-obj="formInfo.ref"
              :disabled="formInfo.disabled"
              :data="formInfo.data"
              :field-list="formInfo.fieldList"
              :rules="formInfo.rules"
              :label-width="formInfo.labelWidth"
            >
            </PageForm>
          </div>
        </div>
        <div class="model-panel">
          <div class="model-panel-title">
            <p>明细信息</p>
          </div>
          <div class="model-panel-body">
            <!-- 条件栏 -->
            <PageFilter :filter-list="filterInfo.list">
              <template v-slot:filter-addProduct>
                <el-button @click="addProduct">添加产品</el-button>
              </template>
              <template v-slot:filter-removeProduct>
                <el-button :disabled="!canRemoveAsset" @click="removeProduct()"
                  >删除产品</el-button
                >
              </template>
            </PageFilter>
            <div class="flex_full_item">
              <el-form ref="tableForm" :model="tableInfo" style="width: 100%">
                <!-- 表格 -->
                <PageTable
                  :refresh="tableInfo.refresh"
                  :init-curpage="tableInfo.initCurpage"
                  v-model:data="tableInfo.data"
                  :pager="false"
                  :tab-index="true"
                  :field-list="tableInfo.fieldList"
                  :handle="tableInfo.handle"
                  :isRowClickSelect="true"
                  :isDynamic="true"
                  @handleEvent="handleEvent"
                >
                </PageTable>
              </el-form>
            </div>
          </div>
        </div>
      </FullScreen>
    </div>
    <!-- 添加产品 -->
    <NewSelectProduct
      v-if="productInfo.visible"
      v-model:showDialog="productInfo.visible"
      v-model:query="productInfo.query.queryMap"
      :api="productInfo.api"
      :query-params="productInfo.query.queryParams"
      :tableKey="productInfo.tableKey"
      :showEditQty="false"
      @callback="selectProduct"
    />
  </div>
</template>

<script setup name="cmVarModify">
import { getProductCustomizeList } from '@/api/core.js'
import { postProductVarieties } from '@/api/cmPreMgt'

const { proxy } = getCurrentInstance()
const props = defineProps(['visible', 'title'])
const emits = defineEmits()

const formRefs = ref([])
//表单相关
const formInfo = ref({
  ref: null,
  data: {},
  fieldList: [
    {
      label: '品种名称',
      value: 'varietiesName',
      type: 'input',
    },
  ],
  rules: {
    varietiesName: [
      {
        required: true,
        message: '请输入品种名称',
        trigger: 'blur',
      },
    ],
  },
  labelWidth: '100px',
})
// 过滤相关配置
const filterInfo = ref({
  query: {},
  list: [
    { type: 'slot', value: 'addProduct' },
    { type: 'slot', value: 'removeProduct' },
  ],
})
// 表格相关
const tableInfo = ref({
  refresh: 1,
  initCurpage: 1,
  data: [],
  selections: [],
  fieldList: [
    { label: '产品编码', value: 'productCode' },
    { label: '产品名称', value: 'commonName' },
    { label: '规格', value: 'standard' },
    { label: '厂家', value: 'brandName' },
    { label: '计量单位', value: 'unitName' },
  ],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '50',
    btList: [
      {
        label: '删除',
        event: removeProduct,
        popconfirmText: '删除后将改变数据,是否继续？',
        show: true,
      },
    ],
  },
})
//选择产品相关
const productInfo = ref({
  api: getProductCustomizeList,
  visible: false,
  tableKey:
    'exceptActualSelectProduct-com.slip.spd.entity.vo.core.CoreProductVONew',
  query: {
    queryMap: {
      id: {
        queryType: 'NOT_IN',
        queryCategory: 'AND',
        value: '',
      },
      varietiesName: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: '',
        ignoreEmptyValue: false,
      },
    },
    queryParams: {
      deptId: null,
    },
  },
})

const showDialog = computed({
  get() {
    return props.visible
  },
  set(val) {
    proxy.$emit('update:visible', val) // 更新父组件visible
  },
})
const canSave = computed(() => {
  return tableInfo.value.data.length
})
const canRemoveAsset = computed(() => {
  return tableInfo.value.selections.length
})
// 触发事件
function handleEvent(event, data) {
  switch (event) {
    case 'tableCheck':
      tableInfo.value.selections = [...data]
      break
  }
}

onMounted(() => {
  proxy.$nextTick(() => {
    formRefs.value = [proxy.$refs['tableForm'], formInfo.value.ref]
  })
})

function save() {
  proxy.$fn.checkForm(formRefs.value).then(() => {
    const details = tableInfo.value.data.filter((item) => item.productId)
    const data = formInfo.value.data
    if (!details.length) {
      proxy.$message({
        duration: 3500,
        type: 'warning',
        showClose: true,
        message: '请添加有效的产品',
      })
      return
    }
    const arr = []
    details.forEach((item) => {
      arr.push({
        productId: item.id,
      })
    })
    data.details = arr
    postProductVarieties(data).then((resp) => {
      if (resp && resp.success) {
        showDialog.value = false
        emits('returnModify', false)
      }
    })
  })
}
//选择产品
function addProduct() {
  productInfo.value.query.queryMap.id.value = null
  if (tableInfo.value.data.length) {
    productInfo.value.query.queryMap.id.value = tableInfo.value.data
      .map((item) => item.id)
      .toString()
  }
  productInfo.value.visible = true
}
//删除产品
function removeProduct(selectRow = undefined) {
  if (selectRow && selectRow.productId) {
    tableInfo.value.data = tableInfo.value.data.filter(
      (row) => row !== selectRow
    )
  } else {
    proxy
      .$confirm('删除后将改变数据,是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
      .then(() => {
        tableInfo.value.data = tableInfo.value.data.filter(
          (row) => !tableInfo.value.selections.includes(row)
        )
      })
  }
}
//选择产品
function selectProduct(rows) {
  if (rows) {
    tableInfo.value.data = rows.concat(tableInfo.value.data)
  }
}
</script>

<style scoped lang="scss"></style>
